<template>
  <div>
    <p>this is home</p>
    <el-button @click="sendMessage">发送消息</el-button>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'Home' })
import { onMounted, onUnmounted, ref } from 'vue'
const websocket = ref<WebSocket>()
const sendMessage = () => {
  if (websocket.value) {
    websocket.value.send('hello world from client')
  }
}
onMounted(() => {
  console.log('home')
  // 连接 websocket server

  if ('WebSocket' in window) {
    websocket.value = new WebSocket('ws://localhost:9000/ws')
    if (websocket) {
      websocket.value.onopen = function () {
        console.log('websocket connected')
      }
      websocket.value.onmessage = function (evt) {
        console.log('received message: ' + evt.data)
      }
      websocket.value.onclose = function () {
        console.log('websocket closed')
      }
      websocket.value.onerror = function () {
        console.log('websocket error')
      }
    }
  } else {
    alert('你的浏览器不支持 WebSocket!')
  }
})
onUnmounted(() => {
  console.log('home unmounted')
  if (websocket.value) {
    websocket.value.close()
  }
})
</script>
